package controllers;

import java.util.*;
import models.Group;
import models.User;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.With;
import play.i18n.Messages;
import play.data.validation.*;

//TODO Faire les modifications du textearea pour la description du groupe
@With(Secure.class)
public class Groups extends Controller {

    @Before
    static void setConnectedUser() {
        if (Security.isConnected()) {
            User user = User.find("byUsername", Security.connected()).first();
            renderArgs.put("user", user);


        }
    }

    public static void list() {
        List<Group> entities = models.Group.all().fetch();
        render(entities);
    }

    public static void create(Group entity) {
        render(entity);
    }

    public static void show(Long id) {
        Group entity = Group.findById(id);
        render(entity);
    }

    public static void edit(Long id) {
        Group entity = Group.findById(id);
        render(entity);
    }

    public static void delete(Long id) {
        Group entity = Group.findById(id);
        entity.delete();
        flash.success(Messages.get("Groups.deleted"));
        Groups.list();
    }

    public static void save(@Valid Group entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));
            render("@create", entity);
        }
        entity.save();
        flash.success(Messages.get("Groups.created"));
        Groups.list();
    }

    public static void update(@Valid Group entity) {
        if (validation.hasErrors()) {
            flash.error(Messages.get("validation"));
            render("@edit", entity);
        }

        entity = entity.merge();

        entity.save();
        flash.success(Messages.get("Groups.updated"));
        Groups.list();
    }
}
